package com.jhc.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhc.bo.UserSaveDetails;
import com.jhc.dto.*;
import com.jhc.entity.*;
import com.jhc.mapper.*;
import com.jhc.service.ICmsTeacherService;
import com.jhc.service.RedisService;
import com.jhc.utils.JHC;
import com.jhc.utils.JwtTokenUtil;
import com.jhc.vo.PageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 教师档案  服务实现类
 * </p>
 *
 * @author zfm
 * @since 2019-11-24
 */
@Service
@Slf4j
public class CmsTeacherServiceImpl extends ServiceImpl<CmsTeacherMapper, CmsTeacher> implements ICmsTeacherService {

    @Autowired
    private BacCollegeMapper bacCollegeMapper;

    @Autowired
    private CmsTeacherMapper cmsTeacherMapper;

    @Autowired
    private CmsRoleMapper cmsRoleMapper;

    @Autowired
    private CmsPermissionMapper cmsPermissionMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserSaveDetails userSaveDetails;

    @Autowired
    private CmsUserMapper cmsUserMapper;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.expiration}")
    private Long redisTime;

//    /**
//     * 获取用户所有权限
//     *
//     * @param staffNumber 用户账号 职工号
//     * @return 用户权限列表
//     */
//    @Override
//    public List<CmsPermission> getPermissionList(String staffNumber) {
//
//        // 查询用户权限值
//        CmsUser cmsAdmin = cmsTeacherMapper.selectOne(new QueryWrapper<CmsUser>()
//                .lambda()
//                .eq(CmsUser::getNumber, staffNumber));
//        if (cmsAdmin == null) {
//            return new ArrayList<>();
//        }
//        try {
//            // 字符串生成对象
//            UserAuthData userAuthData = JSONUtil.toBean(cmsAdmin.getAuthData(), UserAuthData.class);
//            // 权限列表
//            List<String> authList = userAuthData.getAuthList();
//            // 角色列表
//            List<String> roleList = userAuthData.getRoleList();
//            // 查询角色 拿到角色表中的权限值
//            System.out.println(roleList.toString());
//            if (roleList.size() != 0) {
//                List<CmsRole> authRoleList = cmsRoleMapper.selectList(new QueryWrapper<CmsRole>().lambda()
//                        .select(CmsRole::getAuthData)
//                        .in(CmsRole::getId, roleList));
//                // 拿到角色中的权限值并保存
//                for (CmsRole cmsRole : authRoleList) {
//                    UserAuthData roleAuth = JSONUtil.toBean(cmsRole.getAuthData(), UserAuthData.class);
//                    if (roleAuth.getAuthList() != null) {
//                        authList.addAll(roleAuth.getAuthList());
//                    }
//                }
//            }
//            // 去重
//            authList = authList.stream().distinct().collect(Collectors.toList());
//            // 查出权限列表
//            if (authList.size() != 0) {
//                return cmsPermissionMapper.selectList(
//                        new QueryWrapper<CmsPermission>().lambda()
//                                .in(CmsPermission::getValue, authList));
//            }
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        }
//        return new ArrayList<>();
//    }

    /**
     * 用户注册
     *
     * @param cmsRegister 注册实体类
     * @return 是否注册成功
     */
    @Override
    public Boolean register(CmsRegister cmsRegister) {
        //BeanUtils.copyProperties(cmsRegister, cmsUser);
        CmsUser cmsUser = new CmsUser();
        CmsTeacher cmsTeacher = new CmsTeacher();
        cmsTeacher.setDepartmentName(cmsRegister.getDepartmentNumber());

        cmsUser.setNumber(cmsRegister.getNumber());
        cmsUser.setPassword(cmsRegister.getPassword());
        cmsUser.setName(cmsRegister.getName());
        cmsUser.setSex(cmsRegister.getSex());
        cmsUser.setType(cmsRegister.getType());
        cmsUser.setCollegeNumber(cmsRegister.getCollegeNumber());

        // 保留json对象格式
        UserAuthData userAuthData = new UserAuthData();
        userAuthData.setAuthList(new ArrayList<>());
        userAuthData.setRoleList(new ArrayList<>());
        cmsUser.setAuthData(JSON.toJSONString(userAuthData));
        // 查询是否有相通用户名
        if (cmsUserMapper.selectOne(new QueryWrapper<CmsUser>().lambda()
                .eq(CmsUser::getNumber, cmsRegister.getNumber())) != null) {
            return false;
        }

        int insert = cmsTeacherMapper.insert(cmsTeacher);
        if(insert != 1){
            return false;
        }
        cmsUser.setUserDetailId(cmsTeacher.getId());

        // 密码加密
        String encodePassword = passwordEncoder.encode(cmsUser.getPassword());
        cmsUser.setPassword(encodePassword);
        return cmsUserMapper.insert(cmsUser) == 1;
    }

//    /**
//     * 用户登陆
//     *
//     * @param username 用户名
//     * @param password 密码
//     * @return token
//     */
//    @Override
//    public RedisUserInfo login(String username, String password) {
//        String token = null;
//        RedisUserInfo redisUserInfo = new RedisUserInfo();
//        try {
//            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
//            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
//                throw new BadCredentialsException("密码不正确");
//            }
//            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
//                    userDetails, null, userDetails.getAuthorities()
//            );
//            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//            token = jwtTokenUtil.generateToken(userDetails);
//
//            // 获取用户所携带的路由信息
//            List<CmsPermission> cmsPermissionList = getPermissionList(username);
//            List<CmsTreePermission> cmsTreePermissionList = JHC.cmsTreePermissions(cmsPermissionList);
//            redisUserInfo.setStaffNumber(username);
//            //查询老师用户信息
//            CmsUser teacher = cmsTeacherMapper.selectOne(new QueryWrapper<CmsUser>().lambda().eq(CmsUser::getNumber, username));
//            //查询学院信息
//            BacCollege college = bacCollegeMapper.selectOne(new QueryWrapper<BacCollege>().lambda().eq(BacCollege::getNumber, teacher.getCollegeNumber()));
//            if (college != null) {
//                redisUserInfo.setCollegeName(college.getName());
//            }
//            redisUserInfo.setId(teacher.getId());
//            redisUserInfo.setStaffName(teacher.getName());
//            redisUserInfo.setPermissionList(cmsPermissionList);
//            redisUserInfo.setRouter(cmsTreePermissionList);
//            redisUserInfo.setToken(tokenHead + token);
//            redisService.set(username, JSON.toJSONString(redisUserInfo));
//            redisService.expire(username, redisTime);
//
//        } catch (Exception e) {
//            log.warn("登陆异常:{}", e.getMessage());
//        }
//        return redisUserInfo;
//    }

//    /**
//     * 给用户添加权限
//     *
//     * @param cmsUserPermissionAdd 添加权限对象
//     * @return 是否添加成功
//     */
//    @Override
//    public Boolean userAddPermission(CmsUserPermissionAdd cmsUserPermissionAdd) {
//        CmsUser cmsUser = getUserAuth(cmsUserPermissionAdd.getId());
//        if (cmsUser == null) {
//            return false;
//        }
//        // 拿出原本的角色 + 权限 字符串
//        String authStr = cmsUser.getAuthData();
//        // 把字符串转对象
//        UserAuthData userAuthData = JSONUtil.toBean(authStr, UserAuthData.class);
//        // 把新的权限列表设置到对象中
//        userAuthData.setAuthList(cmsUserPermissionAdd.getAuthList());
//        // 把对象转化成json设置到对象中
//        cmsUser.setAuthData(JSONUtil.toJsonStr(userAuthData));
//        // 清除token
//        if (cmsTeacherMapper.updateById(cmsUser) == 1) {
//            clearToken(cmsUserPermissionAdd.getIfFast(), cmsUserPermissionAdd.getId());
//            return true;
//        }
//        return false;
//    }

//    /**
//     * 给用户添加角色
//     *
//     * @param cmsUserRoleAdd 添加角色对象
//     * @return 是否添加成功
//     */
//    @Override
//    public Boolean userAddRole(CmsUserRoleAdd cmsUserRoleAdd) {
//        CmsUser cmsUser = getUserAuth(cmsUserRoleAdd.getId());
//        if (cmsUser == null) {
//            return false;
//        }
//        if (cmsRoleMapper.selectById(cmsUserRoleAdd.getRoleId()) == null) {
//            return false;
//        }
//        // 拿出原本的角色 + 权限 字符串
//        String authStr = cmsUser.getAuthData();
//        // 把字符串转化成对象（原本的）
//        UserAuthData userAuthData = JSONUtil.toBean(authStr, UserAuthData.class);
//        // 把添加的角色ID放进去
//        userAuthData.getRoleList().add(cmsUserRoleAdd.getRoleId());
//        // 把对象转化成json存到对象
//        cmsUser.setAuthData(JSONUtil.toJsonStr(userAuthData));
//        // 清除token
//        if (cmsTeacherMapper.updateById(cmsUser) == 1) {
//            clearToken(cmsUserRoleAdd.getIfFast(), cmsUserRoleAdd.getId());
//            return true;
//        }
//        return false;
//    }

    /**
     * 删除角色ID
     *
     * @param cmsUserRoleAdd 删除角色对象
     * @return
     */
//    @Override
//    public Boolean userRemoveRole(CmsUserRoleAdd cmsUserRoleAdd) {
//        CmsUser cmsUser = getUserAuth(cmsUserRoleAdd.getId());
//        // 如果用户不存在
//        if (cmsUser == null) {
//            return false;
//        }
//        // 如果角色不存在
//        if (cmsRoleMapper.selectById(cmsUserRoleAdd.getRoleId()) == null) {
//            return false;
//        }
//        // 拿出原本的角色 + 权限 字符串
//        String authStr = cmsUser.getAuthData();
//        // 把字符串转化成对象（原本的）
//        UserAuthData userAuthData = JSONUtil.toBean(authStr, UserAuthData.class);
//        // 删除角色ID
//        userAuthData.setRoleList(userAuthData.getRoleList().stream().filter(item -> !cmsUserRoleAdd.getRoleId().equals(item)).collect(Collectors.toList()));
//        // 把对象转化成json存到对象
//        cmsUser.setAuthData(JSONUtil.toJsonStr(userAuthData));
//        // 清除token
//        if (cmsTeacherMapper.updateById(cmsUser) == 1) {
//            clearToken(cmsUserRoleAdd.getIfFast(), cmsUserRoleAdd.getId());
//            return true;
//        }
//        return false;
//    }

//    private void clearToken(boolean ifFast, Long id) {
//        // 判断是否马上登出
//        CmsUser cmsUser = cmsTeacherMapper.selectOne(new QueryWrapper<CmsUser>()
//                .lambda()
//                .select(CmsUser::getNumber)
//                .eq(CmsUser::getId, id));
//        if (ifFast && cmsUser != null) {
//            redisService.remove(cmsUser.getNumber());
//        } else if (!ifFast && cmsUser != null) {
//            redisService.expire(cmsUser.getNumber(), 60 * 60);
//        }
//    }

    /**
     * 根据ID查找用户id和身份信息
     *
     * @param id 用户ID
     * @return 带有id和身份信息的实体对象
     */
//    private CmsUser getUserAuth(Long id) {
//        LambdaQueryWrapper<CmsUser> queryWrapper = new QueryWrapper<CmsUser>()
//                .select("auth_data", "id").lambda()
//                .eq(CmsUser::getId, id);
//        return cmsTeacherMapper.selectOne(queryWrapper);
//    }

    /**
     * 通过页码和每页记录数获取分页数据
     *
     * @param pageVo 封装分页参数
     * @return
     */
    @Override
    public IPage<CmsTeacherViewDto> getTeacherPageData(PageVo<CmsTeacherSearchDto> pageVo) {
        //防止mapper.xml中无法获取filter报错
        if (ObjectUtil.isNull(pageVo.getFilter())) {
            pageVo.setFilter(new CmsTeacherSearchDto());
        }
        //构造分页参数
        CmsTeacherSearchDto searchDto = pageVo.getFilter();
        Page page = new Page(pageVo.getCurrentPage(), pageVo.getPageSize());
        //查询教师表分页数据
        IPage<CmsTeacherViewDto> viewDtoIPage = cmsTeacherMapper.getTeacherPageData(page, searchDto);
        return viewDtoIPage;
    }

    /**
     * 模糊查询班主任列表
     *
     * @param name
     * @return
     */
//    @Override
//    public List<CmsTeacher> getTeacherListByLikeName(String name) {
//        List<CmsTeacher> teacherList = cmsTeacherMapper.selectList(new QueryWrapper<CmsTeacher>().lambda()
//                .like(CmsTeacher::getName, name));
//        return teacherList;
//    }

    /**
     * 校验老师编号列表是否存在
     *
     * @param numbers
     * @return
     */
//    @Override
//    public Boolean isTeacherNumberList(List<String> numbers) {
//        for (String teacherNumber : numbers) {
//            CmsUser teacher = cmsTeacherMapper.selectOne(new QueryWrapper<CmsUser>().lambda().eq(CmsUser::getNumber, teacherNumber));
//            if (teacher == null) {
//                return false;
//            }
//        }
//        return true;
//    }

//    /**
//     * 密码更新
//     * @param cmsUpdatePasswordDto
//     * @return
//     */
//    @Override
//    public boolean updatePassword(CmsUpdatePasswordDto cmsUpdatePasswordDto) {
//        UserDetails userDetails = userDetailsService.loadUserByUsername(cmsUpdatePasswordDto.getNumber());
//        if (!passwordEncoder.matches(cmsUpdatePasswordDto.getOldPassword(), userDetails.getPassword())) {
//            throw new BadCredentialsException("密码不正确");
//        }
//        cmsUpdatePasswordDto.setPassword(passwordEncoder.encode(cmsUpdatePasswordDto.getPassword()));
//        CmsUser cmsUser = new CmsUser();
//        BeanUtils.copyProperties(cmsUpdatePasswordDto, cmsUser);
//        if (cmsTeacherMapper.update(cmsUser, new UpdateWrapper<CmsUser>().lambda()
//                .eq(CmsUser::getNumber, cmsUpdatePasswordDto.getNumber())) == 1) {
//            redisService.remove(cmsUser.getNumber());
//            return true;
//        }
//        return false;
//    }

    /**
     * 更新用户信息
     *
     * @param cmsTeacherUpdate
     * @return
     */
    @Override
    public boolean updateInfo(CmsTeacherUpdate cmsTeacherUpdate) {
        CmsTeacher cmsTeacher = new CmsTeacher();
        cmsTeacher.setDepartmentName(cmsTeacherUpdate.getDepartmentNumber());
        CmsUser cmsUser = new CmsUser();
        cmsUser.setName(cmsTeacherUpdate.getName());
        cmsUser.setSex(cmsTeacherUpdate.getSex());
        cmsUser.setCollegeNumber(cmsTeacherUpdate.getCollegeNumber());

        cmsUser.setNumber(userSaveDetails.getCmsUser().getNumber());

        int update = cmsTeacherMapper.update(cmsTeacher, new UpdateWrapper<CmsTeacher>().lambda().eq(CmsTeacher::getId, userSaveDetails.getCmsUser().getUserDetailId()));
        if(update != 1){
            return false;
        }
        return cmsUserMapper.update(cmsUser, new UpdateWrapper<CmsUser>().lambda().eq(CmsUser::getNumber, cmsUser.getNumber())) == 1;
    }
}
